package com.maiji.cloud.aop;

import com.maiji.cloud.entities.shopingmall.ShipmentsInfoEntity;
import com.maiji.cloud.entities.shopingmall.ShopingOrder;
import com.maiji.cloud.entities.shopingmall.ShoppingOrderRefundEntity;
import com.maiji.cloud.listener.MyListener;
import com.maiji.cloud.response.BaseDataResDto;
import com.maiji.cloud.response.BaseResDto;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.response.shopingmall.ShopingOrderResData;
import com.maiji.cloud.service.ShopingOrderRefundService;
import com.maiji.cloud.service.ShopingOrderService;
import com.maiji.cloud.utils.CommonIntValueEnum;
import com.maiji.cloud.utils.JpushUtil;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
@Aspect
public class WebControllerAop {

    Logger logger = LoggerFactory.getLogger(WebControllerAop.class);
    @Value("${apnsProduction}")
    private Boolean apnsProduction;
    @Autowired
    private ShopingOrderService shopingOrderService;
    @Autowired
    private ShopingOrderRefundService shopingOrderRefundService;

    // 提交订单10分钟后推送
    @AfterReturning(value="execution(* com.maiji.cloud.service.ShopingOrderService.orderSubmit(..))", returning = "baseDataResDto")
    public void doAfterReturningOrderSubmit(BaseDataResDto<ShopingOrderResData> baseDataResDto){
        MyListener.AUTOCANCELORDERTIMER.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    String orderId = baseDataResDto.getData().getUuId();
                    ShopingOrder order = shopingOrderService.selectById(orderId);
                    if (order.getStatus() == CommonIntValueEnum.SHOPPING_ORDER_STATUS_STAY_PAY.getValue())
                        JpushUtil.sendToAlias(order.getUserId(), "您有订单等待付款，请及时处理：订单编号【" + order.getOrderNo() + "】", apnsProduction);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, TimeUnit.MINUTES.toMillis(MyListener.AUTOPUSHMINUTES));
    }

    // 订单发货后推送
    @AfterReturning(value="execution(* com.maiji.cloud.service.ShipmentsInfoService.orderSend(..)) && args(data)")
    public void doAfterReturningOrderSend(List<ShipmentsInfoEntity> data){
        List<String> orderIds = data.parallelStream().map(ShipmentsInfoEntity::getOrderId).collect(Collectors.toList());
        List<ShopingOrder> orders = shopingOrderService.selectBatchIds(orderIds);
        orders.parallelStream().forEach(order -> {
            JpushUtil.sendToAlias(order.getUserId(), "您有订单已发货，请关注物流信息及时收货：订单编号【" + order.getOrderNo() + "】", apnsProduction);
        });
    }

    // 退款完成后推送
    @AfterReturning(value="execution(* com.maiji.cloud.service.CapitalMainLogService.executeRefund(..)) && args(orderRefundId)", returning = "baseResDto")
    public void doAfterReturningExecuteRefund(String orderRefundId, BaseResDto baseResDto){
        if (baseResDto.getStatus() == Status.SUCCESS) {
            ShoppingOrderRefundEntity shoppingOrderRefund = shopingOrderRefundService.selectById(orderRefundId);
            ShopingOrder shopingOrder = shopingOrderService.selectById(shoppingOrderRefund.getOrderId());
            String payType = "";
            if (shopingOrder.getPayType() == 1) payType = "余额";
            if (shopingOrder.getPayType() == 2) payType = "微信";
            if (shopingOrder.getPayType() == 3) payType = "支付宝";
            JpushUtil.sendToAlias(shopingOrder.getUserId(), "您的退款申请已处理完结，" +
                    shoppingOrderRefund.getRefundManey() + "元退款至您的" + payType + "：订单编号【" + shopingOrder.getOrderNo() + "】", apnsProduction);
        }
    }

    // 分销申请审核后推送
    @AfterReturning(value="execution(* com.maiji.cloud.service.DistributionService.examineDbApply(..)) && args(userId, status)")
    public void doAfterReturningExamineDbApply(String userId, Integer status){
        JpushUtil.sendToAlias(userId, "您的分销申请审核" + (status == 1 ? "通过" : "未通过"), apnsProduction);
    }

    /*@Around("execution(* com.maiji.cloud.controller..*(..))")
    public Object doAroundService(ProceedingJoinPoint proceedingJoinPoint){
        String requestId = UUID_MD5.getUUID();
        try {
            Object[] args = proceedingJoinPoint.getArgs();
            logger.info("doAroundService: " + requestId + " ===>> "+proceedingJoinPoint.getSignature().getName() + ": args ===>> " + JSON.toJSONString(args));
            Object object=proceedingJoinPoint.proceed();
            logger.info("doAroundService: " + requestId + " ===>> "+proceedingJoinPoint.getSignature().getName() + ": return ===>> " + JSON.toJSONString(object));
            return object;
        } catch (Throwable throwable) {
            logger.info("doAroundService: " + requestId + " ===>> "+proceedingJoinPoint.getSignature().getName() + ": throwable");
            throwable.printStackTrace();
        }
        return null;
    }*/

}
